package com.hzk.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzk.pojo.*;
import com.hzk.service.*;
import com.hzk.utils.IdUtils;
import com.hzk.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 前端控制器
 *
 * </p>linux:1000线程（1）吞吐量：60.4
 * </p>linux:1000线程（2）吞吐量：4.8
 * </p>linux:1000线程（3）吞吐量：4.8
 * </p>windows:1000线程（1）吞吐量：231
 * </p>windows:1000线程（2）吞吐量：228
 * </p>linux:100000线程（3）吞吐量：4.6
 * </p>windows:100000线程（2）吞吐量：277
 * </p>windows:100000线程（3）吞吐量：1619
 * </p>windows:100000线程（4）吞吐量：4335
 * </p>windows:100000线程（5）吞吐量：4439.
 *
 * @author jack
 * @since 2022-02-25
 */
@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodController {
    @Autowired
    IOrdersService iOrdersService;
    @Autowired
    IOrderService iOrderService;
    @Autowired
    IGoodService iGoodService;
    @Autowired
    ISanbankcService iSanbankcService;
    @Autowired
    IUserBasicService iUserBasicService;
    @Autowired
    ISeckillOrderService iSeckillOrderService;
    @Autowired
    IGoodsService iGoodsService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    /* @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
     @ResponseBody
     public String toLogin(HttpServletRequest request, HttpServletResponse
             response, Model model, UserBasic user) {
         ValueOperations valueOperations = redisTemplate.opsForValue();
         //Redis中获取页面，如果不为空，直接返回页面
         String html = (String) valueOperations.get("goodsList");
         if (!StringUtils.isEmpty(html)) {
             return html;
         }
         model.addAttribute("user", user);
         model.addAttribute("goodsList", iGoodsService.findGoodsVo());
         // return "goodsList";
         //如果为空，手动渲染，存入Redis并返回
         WebContext context = new WebContext(request, response,
                 request.getServletContext(), request.getLocale(),
                 model.asMap());
         html = thymeleafViewResolver.getTemplateEngine().process("hello1",
                 context);
         if (!StringUtils.isEmpty(html)) {
             valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
         }
         return html;
     }*/
    @RequestMapping(value = "/toList")
    @ResponseBody

    public RespBean toLogin(@CaseUser UserBasic userBasic) {


     /*  String token = request.getHeader("token");
       UserBasic user = (UserBasic) redisTemplate.opsForValue().get("UserBasic:"+token);
       if (user==null){
           return RespBean.error(RespBeanEnum.NULL_USER_ERROR);
       }*/
        if (userBasic == null) {
            return RespBean.error(RespBeanEnum.NULL_USER_ERROR);
        }

        List<GoodsVo> goodsVo = iGoodsService.findGoodsVo();

        if (goodsVo == null) {
            return RespBean.error(RespBeanEnum.NULLGOOD_ERROR);
        }
        Iterator<GoodsVo> iterator = goodsVo.iterator();
        while (iterator.hasNext()) {

            GoodsVo good = iterator.next();//迭代器获取每一个商品的信息
            goodsStateVo goodsStateVo = new goodsStateVo();
            Date startDate = good.getStartDate();
            Date endDate = good.getEndDate();


            Date date = new Date();
            if (date.getTime() - startDate.getTime() < 0) {//当前时间减去开始时间
                //秒杀还未开始
                //毫秒要除以1千
                goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));//进行中的话返回的毫秒数
                goodsStateVo.setMilliseconds((int) ((startDate.getTime() - date.getTime())));
                goodsStateVo.setGoodsState(0);
                good.setGoodsStateVo(goodsStateVo);
            } else if (date.getTime() - endDate.getTime() > 0) {
                //秒杀已经结束
                goodsStateVo.setMillingseconds(0);//((int) ((startDate.getTime()-new Date().getTime())));//进行中的话返回的毫秒数
                goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));//进行中的话返回的毫秒数
                goodsStateVo.setGoodsState(2);
                good.setGoodsStateVo(goodsStateVo);
            } else if (date.getTime() - startDate.getTime() > 0 && date.getTime() - endDate.getTime() < 0) {
                //秒杀进行中
                goodsStateVo.setMilliseconds(0);//((int) ((startDate.getTime()-new Date().getTime())));//进行中的话返回的毫秒数
                goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));
                goodsStateVo.setGoodsState(1);
                good.setGoodsStateVo(goodsStateVo);

            } else {
                goodsStateVo.setGoodsState(-1);
                good.setGoodsStateVo(goodsStateVo);
            }
        }


        return ListVo.success(goodsVo);
    }


    /*@RequestMapping(value = "toDetail/{goodsId}")
    @ResponseBody
    public RespBean toDetail(@PathVariable Long goodsId, UserBasic user) {
        if (user == null) {
            return RespBean.error(RespBeanEnum.NULL_USER_LIST);
        }
        GoodsVo good = iGoodsService.findGoodsByid(goodsId);
        Date startDate = good.getStartDate();
        Date endDate = good.getEndDate();
        int secKillStatus = 0;
        int remainSeconds = 0;
        Date date = new Date();
        if (date.getTime() - startDate.getTime() < 0) {
            //秒杀还未开始
            //毫秒要除以1千
            remainSeconds = (int) ((startDate.getTime() - date.getTime()) / 1000);
        } else if (date.getTime() - endDate.getTime() > 0) {
            //秒杀已经结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else if (date.getTime() - startDate.getTime() > 0 && date.getTime() - endDate.getTime() < 0) {
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        } else {
            secKillStatus = -1;
            remainSeconds = -1;
        }
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setGoodsVo(good);
        goodsDetailVo.setRemainSeconds(remainSeconds);
        goodsDetailVo.setSecKillStatus(secKillStatus);
        goodsDetailVo.setUser(user);
        return RespBean.success(goodsDetailVo);
    }*/
    @RequestMapping(value = "toDetail")
    @ResponseBody
    public RespBean toDetail(@CaseUser UserBasic userBasic, Long goodsid) {
        if (userBasic == null) {
            return RespBean.error(RespBeanEnum.NULL_USER_ERROR);
        }

        GoodsVo good = iGoodsService.findGoodsByid(goodsid);

        if (good == null) {
            return RespBean.error(RespBeanEnum.NULLGOOD_ERROR);
        }


        goodsStateVo goodsStateVo = new goodsStateVo();
        Date startDate = good.getStartDate();
        Date endDate = good.getEndDate();


        Date date = new Date();
        if (date.getTime() - startDate.getTime() < 0) {//当前时间减去开始时间
            //秒杀还未开始
            //毫秒要除以1千
            goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));//进行中的话返回的毫秒数
            goodsStateVo.setMilliseconds((int) ((startDate.getTime() - date.getTime())));
            goodsStateVo.setGoodsState(0);
            good.setGoodsStateVo(goodsStateVo);
        } else if (date.getTime() - endDate.getTime() > 0) {
            //秒杀已经结束
            goodsStateVo.setMillingseconds(0);//((int) ((startDate.getTime()-new Date().getTime())));//进行中的话返回的毫秒数
            goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));//进行中的话返回的毫秒数
            goodsStateVo.setGoodsState(2);
            good.setGoodsStateVo(goodsStateVo);
        } else if (date.getTime() - startDate.getTime() > 0 && date.getTime() - endDate.getTime() < 0) {
            //秒杀进行中
            goodsStateVo.setMilliseconds(0);//((int) ((startDate.getTime()-new Date().getTime())));//进行中的话返回的毫秒数
            goodsStateVo.setMillingseconds((int) ((endDate.getTime() - new Date().getTime())));
            goodsStateVo.setGoodsState(1);
            good.setGoodsStateVo(goodsStateVo);

        } else {
            goodsStateVo.setGoodsState(-1);
            good.setGoodsStateVo(goodsStateVo);
        }


        return ListVo.success(good);
    }


    @RequestMapping(value = "/toBasicList")
    @ResponseBody

    public RespBean toBasicList(@CaseUser UserBasic userBasic) {


     /*  String token = request.getHeader("token");
       UserBasic user = (UserBasic) redisTemplate.opsForValue().get("UserBasic:"+token);
       if (user==null){
           return RespBean.error(RespBeanEnum.NULL_USER_ERROR);
       }*/
        if (userBasic == null) {
            return RespBean.error(RespBeanEnum.NULL_USER_ERROR);
        }

        List<Good> goods = iGoodService.findGood();

        if (goods == null) {
            return RespBean.error(RespBeanEnum.NULLGOOD_ERROR);
        }

        /*while (iterator.hasNext()) {

            GoodsVo good = iterator.next();//迭代器获取每一个商品的信息
            goodsStateVo goodsStateVo = new goodsStateVo();
            Date startDate = good.getStartDate();
            Date endDate = good.getEndDate();


            Date date = new Date();
            if (date.getTime() - startDate.getTime() < 0) {//当前时间减去开始时间
                //秒杀还未开始
                //毫秒要除以1千
                goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));//进行中的话返回的毫秒数
                goodsStateVo.setMilliseconds((int) ((startDate.getTime() - date.getTime())));
                goodsStateVo.setGoodsState(0);
                good.setGoodsStateVo(goodsStateVo);
            } else if (date.getTime() - endDate.getTime() > 0) {
                //秒杀已经结束
                goodsStateVo.setMillingseconds(0);//((int) ((startDate.getTime()-new Date().getTime())));//进行中的话返回的毫秒数
                goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));//进行中的话返回的毫秒数
                goodsStateVo.setGoodsState(2);
                good.setGoodsStateVo(goodsStateVo);
            } else if (date.getTime() - startDate.getTime() > 0 && date.getTime() - endDate.getTime() < 0) {
                //秒杀进行中
                goodsStateVo.setMilliseconds(0);//((int) ((startDate.getTime()-new Date().getTime())));//进行中的话返回的毫秒数
                goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));
                goodsStateVo.setGoodsState(1);
                good.setGoodsStateVo(goodsStateVo);

            } else {
                goodsStateVo.setGoodsState(-1);
                good.setGoodsStateVo(goodsStateVo);
            }
        }*/
        return ListVo.success(goods);
    }

    @RequestMapping(value = "toBasicDetail")
    @ResponseBody
    public RespBean toBasicDetail(@CaseUser UserBasic userBasic, Long goodsid) {
        if (userBasic == null) {
            return RespBean.error(RespBeanEnum.NULL_USER_ERROR);
        }

        Good good = iGoodService.findGoodsByid(goodsid);

        if (good == null) {
            return RespBean.error(RespBeanEnum.NULLGOOD_ERROR);
        }


      /*  goodsStateVo goodsStateVo = new goodsStateVo();
        Date startDate = good.getStartDate();
        Date endDate = good.getEndDate();


        Date date = new Date();
        if (date.getTime() - startDate.getTime() < 0) {//当前时间减去开始时间
            //秒杀还未开始
            //毫秒要除以1千
            goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));//进行中的话返回的毫秒数
            goodsStateVo.setMilliseconds((int) ((startDate.getTime() - date.getTime())));
            goodsStateVo.setGoodsState(0);
            good.setGoodsStateVo(goodsStateVo);
        } else if (date.getTime() - endDate.getTime() > 0) {
            //秒杀已经结束
            goodsStateVo.setMillingseconds(0);//((int) ((startDate.getTime()-new Date().getTime())));//进行中的话返回的毫秒数
            goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));//进行中的话返回的毫秒数
            goodsStateVo.setGoodsState(2);
            good.setGoodsStateVo(goodsStateVo);
        } else if (date.getTime() - startDate.getTime() > 0 && date.getTime() - endDate.getTime() < 0) {
            //秒杀进行中
            goodsStateVo.setMilliseconds(0);//((int) ((startDate.getTime()-new Date().getTime())));//进行中的话返回的毫秒数
            goodsStateVo.setMillingseconds((int) ((endDate.getTime() - startDate.getTime())));
            goodsStateVo.setGoodsState(1);
            good.setGoodsStateVo(goodsStateVo);

        } else {
            goodsStateVo.setGoodsState(-1);
            good.setGoodsStateVo(goodsStateVo);
        }*/

        return ListVo.success(good);
    }

    @RequestMapping(value = "buy")
    @ResponseBody
    public RespBean buy(@CaseUser UserBasic user, Long goodsid, int money) {
        if (user == null) {
            return RespBean.error(RespBeanEnum.NULL_USER_ERROR);
        }
        UserBasic userBasic = iUserBasicService.getById(user.getId());
        Good good = iGoodService.findGoodsByid(goodsid);
        if (good == null) {
            return RespBean.error(RespBeanEnum.NULLGOOD_ERROR);
        }
        if (good.getGoodsStock() < 1) {//普通库存
            return RespBean.error(RespBeanEnum.NULLGOODS_ERROR);
            /*throw new GabalException(RespBeanEnum.NULLGOODS_ERROR);*/
        }
        if (good.getStartMoney() > money) {
            return RespBean.error(RespBeanEnum.aaaa_ERROR);
        }

        if (!(userBasic.getCardMoney() > money)) {
            return RespBean.error(RespBeanEnum.a_ERROR);
        }
        if (money > good.getMaxMoney()) {
            return RespBean.error(RespBeanEnum.aaa_ERROR);

        }
        if (money > good.getDayMaxMoney()) {
            return RespBean.error(RespBeanEnum.aa_ERROR);
        }

        Orders order = new Orders();
        /*id=SnowFlake.getInstance().nextId();*/
        userBasic.setCardMoney(userBasic.getCardMoney() - money);
        iUserBasicService.updateById(userBasic);
        Long id = Long.parseLong(IdUtils.getPrimaryKey());
        order.setId(id);
        order.setUserId(userBasic.getId());
        order.setGoodsId(good.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(good.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(BigDecimal.valueOf(Long.parseLong(String.valueOf(money))));
        order.setOrderChannel(1);
        order.setStatus("已支付");
//        Sanbankc byId = iSanbankcService.getById(1);
//        iSanbankcService.updatei(Long.parseLong(money+"")+byId.getAccountMoney());
        order.setCreateDate(new Date());
        iOrdersService.save(order);

        return ListVo.success();
    }

    @RequestMapping(value = "order")
    @ResponseBody
    public RespBean buy(@CaseUser UserBasic user) {
        if (user == null) {
            return RespBean.error(RespBeanEnum.NULL_USER_ERROR);
        }
        SeckillOrder seckillOrders = iSeckillOrderService.select(user);
        if (seckillOrders == null) {
            return RespBean.error(RespBeanEnum.NUL_LIST);
        }
        Order byId = iOrderService.getByIds(seckillOrders.getOrderId());
        return RespBean.success(byId);

    }


}

